package com.syqc.custom

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.appcompat.widget.AppCompatImageView

/**
 * 可拖动的 ImageView，支持位置持久化保存和恢复，同时支持点击事件。
 */
class ScrollImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val prefs: SharedPreferences by lazy {
        context.getSharedPreferences("ScrollImageViewPrefs", Context.MODE_PRIVATE)
    }

    private var lastTouchX = 0f
    private var lastTouchY = 0f
    private var isDragging = false // 标记是否正在拖动

    init {
        isClickable = true // 确保视图可点击
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                restorePosition()
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val parentWidth = (parent as? ViewGroup)?.width?.toFloat() ?: width.toFloat()
        val parentHeight = (parent as? ViewGroup)?.height?.toFloat() ?: height.toFloat()

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchX = event.rawX
                lastTouchY = event.rawY
                isDragging = false // 重置拖动状态
                return true // 消费 DOWN 事件，但不阻止后续判断
            }

            MotionEvent.ACTION_MOVE -> {
                val dx = event.rawX - lastTouchX
                val dy = event.rawY - lastTouchY

                // 判断是否达到拖动阈值（例如 5 像素）
                if (!isDragging && (kotlin.math.abs(dx) > 5 || kotlin.math.abs(dy) > 5)) {
                    isDragging = true
                }

                if (isDragging) {
                    val newLeft = (left + dx).coerceIn(0f, parentWidth - width)
                    val newTop = (top + dy).coerceIn(0f, parentHeight - height)
                    updatePosition(newLeft, newTop)
                    lastTouchX = event.rawX
                    lastTouchY = event.rawY
                    return true // 拖动时消费事件
                }
            }

            MotionEvent.ACTION_UP -> {
                if (isDragging) {
                    savePosition()
                } else {
                    // 如果不是拖动，触发点击事件
                    performClick()
                }
            }
        }
        return super.onTouchEvent(event)
    }

    override fun performClick(): Boolean {
        // 确保点击事件的默认行为可以触发
        return super.performClick()
    }

    private fun updatePosition(left: Float, top: Float) {
        layout(
            left.toInt(),
            top.toInt(),
            (left + width).toInt(),
            (top + height).toInt()
        )
    }

    private fun savePosition() {
        prefs.edit()
            .putFloat("lastX", left.toFloat())
            .putFloat("lastY", top.toFloat())
            .apply()
    }

    private fun restorePosition() {
        val parentWidth = (parent as? ViewGroup)?.width?.toFloat() ?: width.toFloat()
        val parentHeight = (parent as? ViewGroup)?.height?.toFloat() ?: height.toFloat()

        val defaultX = parentWidth - width
        val defaultY = (parentHeight - height) / 2

        val x = prefs.getFloat("lastX", defaultX)
        val y = prefs.getFloat("lastY", defaultY)

        updatePosition(
            x.coerceIn(0f, parentWidth - width),
            y.coerceIn(0f, parentHeight - height)
        )
    }
}